import {
  Router
} from 'express'
const router = Router();
import _ from 'lodash'
import mysql from '../libs/mysql';
import util from '../util';
let tagsSql = `select t.name ,t.id, t.articles_num from tags as t 
              where t.deleted_at is null
              order by t.articles_num desc`;
/* GET users listing. */
router.get('/allData', async (req, res, next) => {
  try {
    let myConnect = await mysql.getConnect();
    let sql = `select SQL_CALC_FOUND_ROWS a.title,a.created_at, a.articles_img ,a.id ,a.introduction ,a.category_id,a.read_num,c.name as category_name,a.comment_num, 
              t.name as tag_name from articles as a 
              left join category as c on a.category_id = c.id 
              left join tags as t on a.tag_id = t.id
              where a.deleted_at is null
              order by a.is_top desc,a.created_at desc limit ? ; SELECT FOUND_ROWS()`;
    let count = 10;
    let page = 1;
    let sqlParams = null;
    let tagParams = null;
    if(+req.body.page){
      page = +req.body.page;
    }
    let offset = (page-1)*count;
    sqlParams = [offset,count]
    
    if(req.body.tag_id){
      sql = `select SQL_CALC_FOUND_ROWS a.title, 
      a.articles_img ,a.id ,a.introduction ,a.created_at,a.category_id ,a.read_num,a.comment_num, 
      c.name as category_name,t.name as tag_name from articles as a
      left join category as c on a.category_id = c.id 
      left join tags as t on a.tag_id = t.id 
      where a.deleted_at is null 
      and t.id = ${myConnect.escape(req.body.tag_id)} 
      order by a.is_top desc,a.created_at desc limit ? ; SELECT FOUND_ROWS()`;
    }
    if(req.body.category_id){
      sql = `select SQL_CALC_FOUND_ROWS a.title, a.articles_img ,a.created_at ,a.id ,a.introduction ,a.category_id ,a.read_num,a.comment_num, 
      c.name as category_name,t.name as tag_name from articles as a 
      left join category as c on a.category_id = c.id 
      left join tags as t on a.tag_id = t.id 
      where a.deleted_at is null and c.id = ${myConnect.escape(req.body.category_id)}
      order by a.is_top desc,a.created_at desc limit ? ; SELECT FOUND_ROWS()`;

    }
    let tags = await mysql.query(myConnect, tagsSql);
    let articles = await mysql.query(myConnect,sql,sqlParams);
    let resultCount = articles[1][0]['FOUND_ROWS()'];
    await mysql.release(myConnect);
    res.send(util.resSuccess({
      data: {
        articles:articles[0],
        tags,
        count:resultCount,
        curPage:page,
        pageCount :Math.ceil(resultCount / count)
      }
    }))
  } catch (error) {
    next(error);
  }
})
router.get('/article/:id', async (req, res, next) => {
  try {
    let myConnect = await mysql.getConnect();
    let id = req.params.id;
    
    let sql = `select a.title,a.user_id, a.articles_img,a.read_num, a.keyword ,a.id , a.introduction,a.content ,a.category_id ,a.tag_id 
               from articles as a where id = ? limit 1`;
    let tags = await mysql.query(myConnect, tagsSql);
    let articles = await mysql.query(myConnect, sql,id);
    let commentSql = `SELECT id,p_id,content,username,email,created_at 
                      FROM comments WHERE articles_id = ? AND p_id = 0 order by created_at desc`;
    let commentFirstResult = await mysql.query(myConnect,commentSql,id);
    let childCommentSql = `SELECT id,p_id,content,username,email,created_at FROM comments WHERE articles_id = ? AND p_id <> 0 order by created_at desc`;
    let childCommentResult = await mysql.query(myConnect,childCommentSql,id); 
    //更新阅读数量
    await mysql.query(myConnect,`UPDATE articles SET read_num = read_num + 1 WHERE id=${myConnect.escape(id)}`)
    await mysql.release(myConnect);
    _.map(commentFirstResult,(item)=>{
      
      let child =zTree(item.id)
      item.commentList = child
      // item.child = 
    });
    function zTree(pid){
      let child = []
      if(!childCommentResult.length){
        return child;
      }
      child = _.remove(childCommentResult,(childItem)=>{
        return childItem.p_id == pid
      })
      if(child.length){
        _.map(child,(item)=>{
          item.commentList = zTree(item.id)
        })
      }
      return child;
    }
    if(articles.length){
      res.send(util.resSuccess({
        data: {
          item:articles[0],
          tags,
          comment:commentFirstResult,
          // childComment:childCommentResult
        }
      }))
    }
  } catch (err) {
    next(err)
  }
})
router.post('/article/addComment',async(req,res,next)=>{
  let {articles_id,p_id,content,username,email} = req.body;
  let sql = `insert into comments set ?`
  let params = {
    articles_id,
    p_id,
    content,
    username,
    email,
  }
  let myConnect = await mysql.getConnect();
  let comment = await mysql.query(myConnect, sql,params);
  //更新阅读数量
  await mysql.query(myConnect,`UPDATE articles SET comment_num = comment_num + 1 WHERE id=${myConnect.escape(articles_id)}`)
  await mysql.release(myConnect);
  
  res.send(util.resSuccess({
    data:comment
  }))
})

export default router;